package cn.cuilan.hutool.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.Watcher;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.WatchEvent;

/**
 * 文件监控
 *
 * @author zhangyan
 * @since 2022/2/14
 */
@Slf4j
public class FileSystemWatchService {

    public static void main(String[] args) {
        File file = FileUtil.file("/Users/zhangyan/tmp");
        // 监控所有事件
        WatchMonitor monitor = WatchMonitor.create(file, WatchMonitor.EVENTS_ALL);
        monitor.setWatcher(new Watcher() {
            @Override
            public void onCreate(WatchEvent<?> watchEvent, Path path) {
                Object obj = watchEvent.context();
                log.info("创建: {} - {}", path, obj);
            }

            @Override
            public void onModify(WatchEvent<?> watchEvent, Path path) {
                Object obj = watchEvent.context();
                log.info("修改: {} - {}", path, obj);
            }

            @Override
            public void onDelete(WatchEvent<?> watchEvent, Path path) {
                Object obj = watchEvent.context();
                log.info("删除: {} - {}", path, obj);
            }

            @Override
            public void onOverflow(WatchEvent<?> watchEvent, Path path) {
                Object obj = watchEvent.context();
                log.info("丢失: {} - {}", path, obj);
            }
        });
        // 设置监听目录的最大深入，目录层级大于制定层级的变更将不被监听，默认只监听当前层级目录
        monitor.setMaxDepth(2);
        // 启动监听
        monitor.start();
    }

}
